# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)
require(gbm)
library(caret)
library(tidyverse)
library(readxl)
library(writexl)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.xlsx", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--index", default = "", type = "character", help = "index")

)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

originalSampleInfo <- read_xlsx(opt$g,col_types = "text") %>%
  rename(ClassNote = Group)
originalSampleInfo

sampleInfo <- originalSampleInfo %>%
  select(c("SampleID", "ClassNote"))

parent <- paste0("./")
createWhenNoExist(parent)

originalData <- read_xlsx(str_c("data.xlsx"),col_types = "text") %>%
  rename(Metabolite = SampleID)

data <- originalData %>%
  mutate(Metabolite = factor(Metabolite, levels = unique(Metabolite))) %>%
  gather("SampleID", "Value", -Metabolite, factor_key = T) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID"))

print("===")
data

trainPercent <- 90
seed <- 1234
set.seed(seed = seed)

trainSampleIds <- data %>%
  .$ClassNote %>%
  unique() %>%
  map(function(classNote) {
    tmpSampleIds <- data %>%
      filter(ClassNote == classNote) %>%
      .$SampleID
    size <- ceiling((length(tmpSampleIds) * trainPercent) / 100)
    sample(tmpSampleIds, size = size, replace = F)
  }) %>%
  flatten_chr()

trainData <- data %>%
  filter(SampleID %in% trainSampleIds)

testSampleIds <- data %>%
  filter(!(SampleID %in% trainSampleIds)) %>%
  .$SampleID

testData <- data %>%
  filter(SampleID %in% testSampleIds)

trainOutTb <- trainData %>%
  select(-c("ClassNote")) %>%
  gather("Metabolite", "Value", -SampleID, factor_key = T) %>%
  spread(SampleID, "Value")

write_xlsx(trainOutTb, "train.xlsx")

testOutTb <- testData %>%
  select(-c("ClassNote")) %>%
  gather("Metabolite", "Value", -SampleID, factor_key = T) %>%
  spread(SampleID, "Value")

write_xlsx(testOutTb, "test.xlsx")

groupOutTb <- originalSampleInfo %>%
  filter(SampleID %in% trainSampleIds) %>%
  rename(Sample = SampleID)

write_xlsx(groupOutTb, "train_group.xlsx")

testGroupOutTb <- originalSampleInfo %>%
  filter(SampleID %in% testSampleIds) %>%
  rename(Sample = SampleID)


write_xlsx(testGroupOutTb, "test_group.xlsx")











